<template>
  <md-nav-bar title="智能导游" />
  <view
    class="container"
    :style="{
      width: '100%',
      height: `calc(100vh - 44px - ${data.statusBarHeight})`,
    }">
    <view class="desc">本回答由AI生成，仅供参考</view>
    <!-- 问答内容 -->
    <view class="content m-top-46">
      <view v-if="data.info?.welcome_text" class="items" :style="{ 'flex-direction': 'row' }">
        <image class="avatar" :src="OneTu" mode="aspectFill" />
        <text
          whitespace="pre-line"
          class="answer"
          :style="{
            background: 'white',
            color: '#333333',
          }">
          {{ data.info.welcome_text }}
        </text>
      </view>
      <view
        class="items"
        v-for="(item, index) in data.list"
        :key="index"
        :style="{ 'flex-direction': item.position == 'left' ? 'row' : 'row-reverse' }">
        <image class="avatar" :src="item.position == 'left' ? OneTu : item.avatar" mode="aspectFill" />
        <text
          whitespace="pre-line"
          class="answer"
          :style="{
            background: item.position == 'left' ? 'white' : '#FF7325',
            color: item.position == 'left' ? '#333333' : 'white',
          }">
          {{ item?.answer || '很抱歉，未搜索到内容显示...' }}
        </text>
      </view>
      <view v-if="data.loading" class="items" :style="{ 'flex-direction': 'row' }">
        <image class="avatar" :src="OneTu" mode="aspectFill" />
        <text
          whitespace="pre-line"
          class="answer"
          :style="{
            background: 'white',
            color: '#333333',
          }">
          {{ '思考中' + loadingDots }}
        </text>
      </view>
    </view>

    <!-- 输入框 -->
    <view class="input">
      <!-- 推荐 -->
      <view class="recommend m-bottom-20">
        <view
          class="item"
          v-for="item in data.info?.recommend_questions"
          :key="item"
          @click="() => handleRecommend(item)">
          {{ item }}
        </view>
      </view>
      <view class="input-item">
        <!-- <image :src="yuyin" class="yuyin" /> -->
        <input v-model="data.message" class="input-content" placeholder="请输入内容..." />
        <view class="send-btn" @click="() => handleSend()">发送</view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref, onUnmounted, watch } from 'vue';
// 组件
import { onLoad, onShow } from '@dcloudio/uni-app';
// 图标
// import yuyin from '@/static/svg/yuyin.svg';
import { cozeChat, cozeGetWelcomeText } from '@/api';
import OneTu from '@/static/images/oneTu.png';

const data = reactive<any>({
  statusBarHeight: uni.getSystemInfoSync().statusBarHeight + 'px',
  list: [],
  info: {},
  message: '',
  conversation_id: '', // 会话ID
  loading: false,
});

// 加载动画相关
const loadingDots = ref<string>('.');
const loadingTimer = ref<any>(null);

// 启动加载动画
const startLoadingAnimation = () => {
  let dotCount = 1;
  loadingDots.value = '.';
  loadingTimer.value = setInterval(() => {
    dotCount = dotCount >= 3 ? 1 : dotCount + 1;
    loadingDots.value = '.'.repeat(dotCount);
  }, 500); // 每500ms更新一次
};

// 停止加载动画
const stopLoadingAnimation = () => {
  if (loadingTimer.value) {
    clearInterval(loadingTimer.value);
    loadingTimer.value = null;
  }
  loadingDots.value = '.';
};

// 监听 loading 状态
watch(
  () => data.loading,
  newVal => {
    if (newVal) {
      startLoadingAnimation();
    } else {
      stopLoadingAnimation();
    }
  }
);

// 推荐
const handleRecommend = (msg: string) => {
  data.message = msg;
  handleSend(msg);
};

const handleSend = (message?: string) => {
  const _message = message || data.message;
  if (!_message) {
    uni.showToast({
      title: '请输入内容',
      icon: 'none',
    });
    return;
  }
  data.list.push({
    avatar: data.info.avatar,
    answer: _message,
    position: 'right',
  });
  fetchCozeChat(_message);
};

/**
 * 接口相关
 */
const fetchCozeGetWelcomeText = async () => {
  try {
    const res = await cozeGetWelcomeText();
    data.info = res.data;
  } catch (error) {}
};

// 聊天
const fetchCozeChat = async (message: string) => {
  data.loading = true;
  data.message = ''; // 重置输入内容
  try {
    const res = await cozeChat({ message, conversation_id: data?.conversation_id });
    data.list.push({
      avatar: OneTu,
      answer: res.data.answer,
      position: 'left',
    });
    data.conversation_id = res.data.conversation_id;
  } catch (error) {}
  data.loading = false;
};

onLoad(() => {
  const configInfo = uni.getStorageSync('configInfo') ? JSON.parse(uni.getStorageSync('configInfo')) : '';
  if (configInfo) {
    data.configInfo = configInfo;
  }
});

onShow(() => {
  fetchCozeGetWelcomeText();
});

// 组件卸载时清除定时器
onUnmounted(() => {
  stopLoadingAnimation();
});
</script>
<style lang="scss" scoped>
.container {
  background: linear-gradient(180deg, #ffecd9 0%, #fffaf4 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24rpx 30rpx;
  box-sizing: border-box;
  .desc {
    color: #808080;
  }
  .content {
    padding-bottom: calc(240rpx + $safe-bottom);
    box-sizing: border-box;
    .items {
      display: flex;
      gap: 13rpx;
      margin-bottom: 25rpx;
      .avatar {
        width: 70rpx;
        height: 70rpx;
        border-radius: 50%;
        overflow: hidden;
        background: white;
      }
      .answer {
        max-width: 530rpx;
        padding: 24rpx 30rpx;
        border-radius: 34rpx;
        font-size: 28rpx;
        font-weight: 500;
      }
    }
  }

  .input {
    position: fixed;
    width: calc(100% - 60rpx);
    left: 30rpx;
    // bottom: calc($safe-bottom + 8rpx);
    bottom: 0;
    padding: 20rpx 0 30rpx;
    background: linear-gradient(to top, #fffaf4 0%, #fffaf4 60%, rgba(255, 250, 244, 0.8) 100%);
    z-index: 10;
    // 推荐相关
    .recommend {
      gap: 24rpx;
      display: flex;
      flex-wrap: wrap;
      .item {
        height: 50rpx;
        line-height: 50rpx;
        background: #ffffff;
        border-radius: 24rpx;
        padding: 0 30rpx;
        box-sizing: border-box;
        font-size: 24rpx;
        box-shadow: 8rpx 8rpx #ccc;
      }
    }
    // 输入框相关
    .yuyin {
      width: 37rpx;
      height: 37rpx;
    }
    .input-item {
      width: 688rpx;
      height: 100rpx;
      background: #ffffff;
      border-radius: 40rpx;
      display: flex;
      align-items: center;
      padding: 0 32rpx;
      box-sizing: border-box;
      font-size: 32rpx;
      box-shadow: 8rpx 8rpx #ccc;
    }
    .input-content {
      flex: 1;
      margin: 0 20rpx;
    }
    .send-btn {
      width: 120rpx;
      height: 60rpx;
      line-height: 60rpx;
      text-align: center;
      background: #ff6614;
      box-shadow: 0rpx 3rpx 8rpx 0rpx rgba(0, 0, 0, 0.2);
      border-radius: 30rpx;
      font-weight: bold;
      font-size: 32rpx;
      color: #ffffff;
    }
  }
}
</style>
